<?php

namespace app\controller;

use app\BaseController;
use app\model\Singers as ModelSingers;
use app\model\Song as ModelSong;
use app\service\TimeService;
use think\Request;

class Song extends BaseController
{
    public function index(Request $request)
    {
        $limit = isset($request['limit']) ? $request['limit'] : 10;
        $keyword = isset($request['keyword']) ? $request['keyword'] : null;
        $singer_id = isset($request['singer_id']) ? $request['singer_id'] : null;

        $query= ModelSong::with('singer')->whereNull('deleted_at');

        if ($keyword) {
            $query->whereLike('song_name', '%' . $keyword . '%');
        }

        if ($singer_id) {
            $query->where('singer_id', $singer_id);
        }

        $query->order('id desc');

        $list = $query->paginate($limit);

        return JsonData(SUCCESS_CODE, "成功", $list);
    }

    public function read($id)
    {
        $item = ModelSong::with('singer')->whereNull('deleted_at')->find(['id' => $id]);

        return JsonData(SUCCESS_CODE, "成功", $item);
    }

    public function update(Request $request, $id)
    {
        $params = $request->post();

        $song = ModelSong::where(['id' => $id, 'deleted_at' => null])->find();

        if (!$song) {
            return JsonData(1001, "歌曲不存在");
        }

        $return = $song->save($params);

        if ($return) {
            return JsonData(SUCCESS_CODE, "成功");
        }
        return JsonData(1000, "失败");
    }

    public function save(Request $request)
    {
        $params    = $request->post();
        $ModelSong = new ModelSong;
        $save      = $ModelSong->save($params);
        if ($save) {
            return JsonData(SUCCESS_CODE, "成功", $save);
        }

        return JsonData(1000, "失败");
    }

    public function delete($id)
    {
        $song = ModelSong::where(['id' => $id, 'deleted_at' => null])->find();

        if (!$song) {
            return JsonData(1001, "歌曲不存在");
        }

        $song->deleted_at = TimeService::getNowDateTime();

        if (!$song->save()) {
            return JsonData(1000, "失败");
        }

        return JsonData(SUCCESS_CODE, "成功");
    }
}